<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>

    <script>
        function calsingle(onechar) {
            var val = 0;
            switch (onechar) {
                case 'C':
                case 'c':
                    val = 12.01;
                    break;
                case 'H':
                case 'h':
                    val = 1.008;
                    break;
                case 'O':
                case 'o':
                    val = 16.00;
                    break;
                case 'N':
                case 'n':
                    val = 14.01;
                    break;
                default :
                val = 0;
            }
            return val;
        }
        function calsum(str) {
            var sum = 0,
                temp = 0,
                index = 0;
            for (var i = 0, j = str.length; i != j; i++) {
                if (i == 0) {
                    index = i;
                    continue;
                }
                if (calsingle(str[i]) != 0 || i+1 >j) {
                    if (temp == 0) {
                        temp = 1;
                    }
                    sum += calsingle(str[index]) * temp;
                    console.log(sum, calsingle(str[index]) * temp)
                    temp = 0;
                    index = i;
                    // [temp, index] = [0, i];
                } else {
                    temp = temp * 10 + parseInt(str[i]);
                }
            }
            sum += calsingle(str[index]);
            console.log(sum);
        }
        calsum('C6H5Oh');
        calsum('C6H51Oh');

    </script>
</body>

</html>